package org.jeecg.modules.zcgl.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.activiti.entity.ActBusiness;
import org.jeecg.modules.activiti.service.IActBusinessService;
import org.jeecg.modules.putstorage.entity.ZcglPutStorageAssets;
import org.jeecg.modules.putstorage.service.IZcglPutStorageAssetsService;
import org.jeecg.modules.zcgl.entity.*;
import org.jeecg.modules.zcgl.service.*;
import org.jeecg.modules.zcgl.vo.AssetFixedCategoryTreeModel;
import org.jeecg.modules.zcgl.vo.AssetFixedParamVo;
import org.jeecg.modules.zcgl.vo.AssetFixedVo;
import org.jeecg.modules.zcglRecipients.entity.ZcglRecipientsAssets;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 固定资产
 * @Author: jeecg-boot
 * @Date: 2021-06-30
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "固定资产")
@RestController
@RequestMapping("/zcgl/assetFixed")
public class AssetFixedController extends JeecgController<AssetFixed, IAssetFixedService> {
    @Autowired
    private IAssetFixedService assetFixedService;
    @Autowired
    private IAssetFixedLogService assetFixedLogService;
    @Autowired
    private IAssetFixedMaintenanceService assetFixedMaintenanceService;

    @Autowired
    private IActBusinessService actBusinessService;

    @Autowired
    private IZcglPutStorageAssetsService iZcglPutStorageAssetsService;
    @Autowired
    private IAssetFixedCategoryService assetFixedCategoryService;

    @RequestMapping(value = "/getJxList")
    public Result<?> getList() {

        List<AssetFixedVo> list = assetFixedService.getJieXianList();
        return Result.ok(list);
    }

    @RequestMapping(value = "/getNewCount")
    public Result<?> getList(@RequestBody JSONObject jsonObject) {

        // 此处转一下防止引号问题带来的报错
        JSONArray list1 = jsonObject.getJSONArray("data");//这样获得的是原格式。
        List list2 = new ArrayList();
        for (int i = 0; i < list1.size(); i++) {
            ZcglRecipientsAssets item = list1.getObject(i, ZcglRecipientsAssets.class);


            AssetFixed assetFixed = assetFixedService.getById(item.getAssetId());
            item.setAssetFixedCategoryId(assetFixed.getAssetFixedCategoryId());
            System.out.println("查看最开始的数量" + assetFixed.getAmount());
            List<ActBusiness> list = actBusinessService.list(new QueryWrapper<ActBusiness>().eq("status", "1").eq("table_name", "zcgl_recipients").like("data", assetFixed.getId()));
            if (list.size() > 0) {
                Double count = 0.0;
                for (int j = 0; j < list.size(); j++) {
                    ActBusiness actBusiness = list.get(j);
                    JSONObject data = JSON.parseObject(actBusiness.getData());
                    JSONArray jsonArray = data.getJSONArray("zcglRecipientsAssetsList");
                    for (int k = 0; k < jsonArray.size(); k++) {
                        if (assetFixed.getSpecifications() == null) {
                            assetFixed.setSpecifications("");
                        }
                        if (assetFixed.getSpecifications().equals(jsonArray.getJSONObject(k).get("assetSpecifications").toString())
                                && assetFixed.getCode().equals(jsonArray.getJSONObject(k).get("assetCode").toString())
                                && assetFixed.getAssetFixedCategoryId().equals(assetFixedService.getById(jsonArray.getJSONObject(k).get("assetId").toString()).getAssetFixedCategoryId())
                        ) {
                            count += Double.valueOf(jsonArray.getJSONObject(k).get("assetAmount").toString());
                        }
                    }
                }
                //显示流程中的数量
                assetFixed.setLcCount(new BigDecimal(count));
                //显示可以入库的数量 因为有的在流程中审核，已经被占用数量
                assetFixed.setTrueCount(assetFixed.getAmount().subtract(new BigDecimal(count)));
                item.setTrueCount(assetFixed.getAmount().subtract(new BigDecimal(count)));
                list2.add(item);
            } else {
                assetFixed.setTrueCount(assetFixed.getAmount());
                assetFixed.setLcCount(new BigDecimal(0.0));
                item.setTrueCount(assetFixed.getAmount());
                list2.add(item);
            }

        }



        return Result.ok(list2);
    }


    @Autowired
    private IZcglAssetFixedCategorySettingService zcglAssetFixedCategorySettingService;

    @RequestMapping(value = "/demo")
    public List demo() {
        List<AssetFixedVo> list = assetFixedService.getJieXianList();
        return list;
    }


    @ApiOperation(value = "固定资产-批量查询物资", notes = "固定资产-批量查询物资")
    @GetMapping(value = "/getMulFixed")
    public Result<?> getMulFixed(String id,
                                 HttpServletRequest req) {
        String[] ids = id.split(",");
        //需要去获取真实的仓库数量 需要减去在审核种的数量
        List<AssetFixed> assetFixeds = assetFixedService.listByIds(Arrays.asList(ids));
        for (int i = 0; i < assetFixeds.size(); i++) {
            AssetFixed assetFixed = assetFixeds.get(i);
            List<ActBusiness> list = actBusinessService.list(new QueryWrapper<ActBusiness>().eq("status", "1").eq("table_name", "zcgl_recipients").like("data", assetFixed.getId()));
            if (list.size() > 0) {
                Double count = 0.0;
                for (int j = 0; j < list.size(); j++) {
                    ActBusiness actBusiness = list.get(j);
                    JSONObject data = JSON.parseObject(actBusiness.getData());
                    JSONArray jsonArray = data.getJSONArray("zcglRecipientsAssetsList");
                    for (int k = 0; k < jsonArray.size(); k++) {
                        if (assetFixed.getSpecifications() == null) {

                            assetFixed.setSpecifications("");
                        }


                        if (assetFixed.getSpecifications().equals(jsonArray.getJSONObject(k).get("assetSpecifications").toString())
                                && assetFixed.getCode().equals(jsonArray.getJSONObject(k).get("assetCode").toString())
                                && assetFixed.getAssetFixedCategoryId().equals(assetFixedService.getById(jsonArray.getJSONObject(k).get("assetId").toString()).getAssetFixedCategoryId())
                        ) {
                            count += Double.valueOf(jsonArray.getJSONObject(k).get("assetAmount").toString());

                        }
                    }
                }
                //显示流程中的数量
                assetFixed.setLcCount(new BigDecimal(count));
                //显示可以入库的数量 因为有的在流程中审核，已经被占用数量
                assetFixed.setTrueCount(assetFixed.getAmount().subtract(new BigDecimal(count)));
            } else {
                assetFixed.setTrueCount(assetFixed.getAmount());
                assetFixed.setLcCount(new BigDecimal(0.0));
            }
        }
        return Result.ok(assetFixeds);
    }

    /**
     * 分页列表查询
     *
     * @param
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "固定资产-分页列表查询")
    @ApiOperation(value = "固定资产-分页列表查询", notes = "固定资产-分页列表查询")
    @GetMapping(value = "/oldList")
    public Result<?> queryPageoldList(AssetFixed assetFixed1,
                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                      @RequestParam(required = false, name = "type") String type,
                                      @RequestParam(required = false, name = "assetType") String assetType,
                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                      HttpServletRequest req) {


        if (assetType != null && !"".equals(assetType)) {
            assetFixed1.setAssetType(assetType);
        }
        //0才是未删除的
        assetFixed1.setDelFlag(0);
        QueryWrapper<AssetFixed> queryWrapper = QueryGenerator.initQueryWrapper(assetFixed1, req.getParameterMap());
        if (oConvertUtils.isNotEmpty(assetFixed1.getAssetFixedCategoryId())) {
//            queryWrapper.or().apply(" asset_fixed_category_id in (select id from zcgl_asset_fixed_category where parent_id ='" + assetFixed1.getAssetFixedCategoryId() + "')");
            queryWrapper.or().apply(" asset_fixed_category_id is null");

        }
//        queryWrapper.apply(" asset_fixed_category_id is null");
        queryWrapper.apply("(asset_fixed_category_id is null  or asset_fixed_category_id = ''  )");

        if ("safe".equals(assetFixed1.getSafeType())) {
            queryWrapper.apply("amount < jiexian");
        }
        if ("2".equals(type)) {
            queryWrapper.apply("amount >0");
        }
        LoginUser loginUser = JwtUtil.getLoginUser();
        if(loginUser==null){
        }
        queryWrapper.last("order by CONVERT( name USING gbk ) COLLATE gbk_chinese_ci asc");
        Page<AssetFixed> page = new Page<AssetFixed>(pageNo, pageSize);
        IPage<AssetFixed> pageList = assetFixedService.page(page, queryWrapper);
        List<ZcglAssetFixedCategorySetting> zcglAssetFixedCategorySettings = zcglAssetFixedCategorySettingService.list(new QueryWrapper<ZcglAssetFixedCategorySetting>().eq("user_id", "1199615897335095297").eq("type", "2"));
        //符合权限的集合
        List<AssetFixed> list1 = new ArrayList<>();
        for (int i = 0; i < pageList.getRecords().size(); i++) {
            AssetFixed assetFixed = pageList.getRecords().get(i);
            List<ActBusiness> list = actBusinessService.list(new QueryWrapper<ActBusiness>().eq("status", "1").eq("table_name", "zcgl_recipients").like("data", assetFixed.getId()));
            //查看是否有权限
            if (list.size() > 0) {
                Double count = 0.0;
                for (int j = 0; j < list.size(); j++) {
                    ActBusiness actBusiness = list.get(j);
                    JSONObject data = JSON.parseObject(actBusiness.getData());
                    JSONArray jsonArray = data.getJSONArray("zcglRecipientsAssetsList");
                    for (int k = 0; k < jsonArray.size(); k++) {
                        if (assetFixed.getSpecifications() == null) {
                            assetFixed.setSpecifications("");
                        }
                        if (assetFixed.getSpecifications().equals(jsonArray.getJSONObject(k).get("assetSpecifications").toString())
                                && assetFixed.getCode().equals(jsonArray.getJSONObject(k).get("assetCode").toString())
                                && assetFixed.getAssetFixedCategoryId().equals(assetFixedService.getById(jsonArray.getJSONObject(k).get("assetId").toString()).getAssetFixedCategoryId())
                        ) {
                            count += Double.valueOf(jsonArray.getJSONObject(k).get("assetAmount").toString());
                        }
                    }
                }
                //显示流程中的数量
                assetFixed.setLcCount(new BigDecimal(count));
                //显示可以入库的数量 因为有的在流程中审核，已经被占用数量
                assetFixed.setTrueCount(assetFixed.getAmount().subtract(new BigDecimal(count)));
            } else {
                assetFixed.setTrueCount(assetFixed.getAmount());
                assetFixed.setLcCount(new BigDecimal(0.0));
            }


        }

        return Result.ok(pageList);
    }

    /**
     * LC专用
     *
     * @param
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "固定资产-分页列表查询")
    @ApiOperation(value = "固定资产-分页列表查询", notes = "固定资产-分页列表查询")
    @GetMapping(value = "/allallList")
    public Result<?> allallList(AssetFixed assetFixed1,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(required = false, name = "type") String type,
                                   @RequestParam(required = false, name = "assetType") String assetType,
                                   @RequestParam(required = false, name = "all") String all,
                                   @RequestParam(name = "pageSize", defaultValue = "1000") Integer pageSize,
                                   HttpServletRequest req) {

        if (assetType != null && !"".equals(assetType)) {
            assetFixed1.setAssetType(assetType);
        }
        //0才是未删除的
        assetFixed1.setDelFlag(0);
        QueryWrapper<AssetFixed> queryWrapper = QueryGenerator.initQueryWrapper(assetFixed1, req.getParameterMap());
        if (oConvertUtils.isNotEmpty(assetFixed1.getAssetFixedCategoryId())) {
            queryWrapper.or().apply(" asset_fixed_category_id in (select id from zcgl_asset_fixed_category where parent_id ='" + assetFixed1.getAssetFixedCategoryId() + "')");
        }
        if ("safe".equals(assetFixed1.getSafeType())) {
            queryWrapper.apply("amount < jiexian");
        }
        if ("2".equals(type)) {
            queryWrapper.apply("amount >0");
        }
        LoginUser loginUser = JwtUtil.getLoginUser();
        queryWrapper.last("order by CONVERT( name USING gbk ) COLLATE gbk_chinese_ci asc");
        Page<AssetFixed> page = new Page<AssetFixed>(pageNo, pageSize);
        IPage<AssetFixed> pageList = assetFixedService.page(page, queryWrapper);


        List<ZcglAssetFixedCategorySetting> zcglAssetFixedCategorySettings = zcglAssetFixedCategorySettingService.list(new QueryWrapper<ZcglAssetFixedCategorySetting>().eq("user_id", loginUser.getId()).eq("type", "2"));
        //符合权限的集合
        List<AssetFixed> list1 = new ArrayList<>();
        List<String> collect = zcglAssetFixedCategorySettings.stream().map(ZcglAssetFixedCategorySetting::getCkId).collect(Collectors.toList());
        System.out.println("pageList我草泥马哦"+pageList);
            for (int i = 0; i < pageList.getRecords().size(); i++) {
                AssetFixed assetFixed = pageList.getRecords().get(i);

                if(!"1".equals(all)){

                    List<ActBusiness> list = actBusinessService.list(new QueryWrapper<ActBusiness>().eq("status", "1").eq("table_name", "zcgl_recipients").like("data", assetFixed.getId()));
                    //查看是否有权限
                    if (list.size() > 0) {
                        Double count = 0.0;
                        for (int j = 0; j < list.size(); j++) {
                            ActBusiness actBusiness = list.get(j);
                            JSONObject data = JSON.parseObject(actBusiness.getData());
                            JSONArray jsonArray = data.getJSONArray("zcglRecipientsAssetsList");
                            for (int k = 0; k < jsonArray.size(); k++) {
                                if (assetFixed.getSpecifications() == null) {
                                    assetFixed.setSpecifications("");
                                }


                                if (assetFixed.getSpecifications().equals(jsonArray.getJSONObject(k).get("assetSpecifications").toString())
                                        && assetFixed.getCode().equals(jsonArray.getJSONObject(k).get("assetCode").toString())
                                        && assetFixed.getAssetFixedCategoryId().equals(assetFixedService.getById(jsonArray.getJSONObject(k).get("assetId").toString()).getAssetFixedCategoryId())
                                ) {
                                    count += Double.valueOf(jsonArray.getJSONObject(k).get("assetAmount").toString());

                                }

                            }
                        }
                        //显示流程中的数量
                        assetFixed.setLcCount(new BigDecimal(count));
                        //显示可以入库的数量 因为有的在流程中审核，已经被占用数量
                        assetFixed.setTrueCount(assetFixed.getAmount().subtract(new BigDecimal(count)));
                    } else {
                        assetFixed.setTrueCount(assetFixed.getAmount());
                        assetFixed.setLcCount(new BigDecimal(0.0));
                    }
                }
                //符合权限的集合
                //符合权限的集合
                System.out.println("我是多少"+all);
                if("1".equals(all)){
                    list1.add(assetFixed);

                }else{
                    if (collect.contains(assetFixed.getAssetFixedCategoryId()) ) {
                        list1.add(assetFixed);
                    }
                }
            }

        pageList.setTotal(list1.size());
        if("1".equals(all)) {
        }else
        {
            for (int i = 0; i < list1.size(); i++) {
                AssetFixed assetFixed = list1.get(i);
                String name = assetFixedCategoryService.getById(assetFixed.getAssetFixedCategoryId()).getName();
                assetFixed.setCkName(name);
            }

        }


        pageList.setRecords(list1);

        return Result.ok(pageList);
    }
    /**
     * 分页列表查询
     *
     * @param
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "固定资产-分页列表查询")
    @ApiOperation(value = "固定资产-分页列表查询", notes = "固定资产-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(AssetFixed assetFixed1,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(required = false, name = "type") String type,
                                   @RequestParam(required = false, name = "assetType") String assetType,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {

        if (assetType != null && !"".equals(assetType)) {
            assetFixed1.setAssetType(assetType);
        }
        //0才是未删除的
        assetFixed1.setDelFlag(0);
        QueryWrapper<AssetFixed> queryWrapper = QueryGenerator.initQueryWrapper(assetFixed1, req.getParameterMap());
        if (oConvertUtils.isNotEmpty(assetFixed1.getAssetFixedCategoryId())) {
            queryWrapper.or().apply(" asset_fixed_category_id in (select id from zcgl_asset_fixed_category where parent_id ='" + assetFixed1.getAssetFixedCategoryId() + "')");
        }
        if ("safe".equals(assetFixed1.getSafeType())) {
            queryWrapper.apply("amount < jiexian");
        }
        if ("2".equals(type)) {
            queryWrapper.apply("amount >0");
        }
        LoginUser loginUser = JwtUtil.getLoginUser();
        List<ZcglAssetFixedCategorySetting> zcglAssetFixedCategorySettings = zcglAssetFixedCategorySettingService.list(new QueryWrapper<ZcglAssetFixedCategorySetting>().eq("user_id", loginUser.getId()).eq("type", "2"));
        List<String> collect = zcglAssetFixedCategorySettings.stream().map(ZcglAssetFixedCategorySetting::getCkId).collect(Collectors.toList());

        queryWrapper.in("asset_fixed_category_id",collect);


        queryWrapper.last("order by CONVERT( name USING gbk ) COLLATE gbk_chinese_ci asc");
        Page<AssetFixed> page = new Page<AssetFixed>(pageNo, pageSize);
        IPage<AssetFixed> pageList = assetFixedService.page(page, queryWrapper);






        //符合权限的集合
        List<AssetFixed> list1 = new ArrayList<>();

        for (int i = 0; i < pageList.getRecords().size(); i++) {
            AssetFixed assetFixed = pageList.getRecords().get(i);
            List<ActBusiness> list = actBusinessService.list(new QueryWrapper<ActBusiness>().eq("status", "1").eq("table_name", "zcgl_recipients").like("data", assetFixed.getId()));
            //查看是否有权限

            if (list.size() > 0) {
                Double count = 0.0;
                for (int j = 0; j < list.size(); j++) {
                    ActBusiness actBusiness = list.get(j);
                    JSONObject data = JSON.parseObject(actBusiness.getData());
                    JSONArray jsonArray = data.getJSONArray("zcglRecipientsAssetsList");
                    for (int k = 0; k < jsonArray.size(); k++) {


                        if (assetFixed.getSpecifications() == null) {

                            assetFixed.setSpecifications("");
                        }


                        if (assetFixed.getSpecifications().equals(jsonArray.getJSONObject(k).get("assetSpecifications").toString())
                                && assetFixed.getCode().equals(jsonArray.getJSONObject(k).get("assetCode").toString())
                                && assetFixed.getAssetFixedCategoryId().equals(assetFixedService.getById(jsonArray.getJSONObject(k).get("assetId").toString()).getAssetFixedCategoryId())
                        ) {
                            count += Double.valueOf(jsonArray.getJSONObject(k).get("assetAmount").toString());

                        }

                    }
                }
                //显示流程中的数量
                assetFixed.setLcCount(new BigDecimal(count));
                //显示可以入库的数量 因为有的在流程中审核，已经被占用数量
                assetFixed.setTrueCount(assetFixed.getAmount().subtract(new BigDecimal(count)));
            } else {
                assetFixed.setTrueCount(assetFixed.getAmount());
                assetFixed.setLcCount(new BigDecimal(0.0));
            }

            //符合权限的集合
            if ( assetFixed.getTrueCount().compareTo(new BigDecimal(0)) == 1) {
                list1.add(assetFixed);
            }
        }
//        pageList.setTotal(list1.size());


        for (int i = 0; i < list1.size(); i++) {
            AssetFixed assetFixed = list1.get(i);
            String name = assetFixedCategoryService.getById(assetFixed.getAssetFixedCategoryId()).getName();
            assetFixed.setCkName(name);
        }
        pageList.setRecords(list1);

        return Result.ok(pageList);
    }

    /**
     * 分页列表查询
     *
     * @param
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "固定资产-分页列表查询")
    @ApiOperation(value = "固定资产-分页列表查询", notes = "固定资产-分页列表查询")
    @GetMapping(value = "/allList")
    public Result<?> queryPageList(AssetFixed assetFixed1,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(required = false, name = "type") String type,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {


        //0才是未删除的
        assetFixed1.setAssetType("");
        assetFixed1.setDelFlag(0);
        QueryWrapper<AssetFixed> queryWrapper = QueryGenerator.initQueryWrapper(assetFixed1, req.getParameterMap());
        if (oConvertUtils.isNotEmpty(assetFixed1.getAssetFixedCategoryId())) {
            queryWrapper.or().apply(" asset_fixed_category_id in (select id from zcgl_asset_fixed_category where parent_id ='" + assetFixed1.getAssetFixedCategoryId() + "')");
        }
        if ("safe".equals(assetFixed1.getSafeType())) {
            queryWrapper.apply("amount < jiexian");
        }
        //查找有库存的
        if ("2".equals(type)) {
            queryWrapper.apply("amount >0");
        }
        queryWrapper.apply("(asset_fixed_category_id is null  or asset_fixed_category_id = ''  )");
        queryWrapper.last("order by CONVERT( name USING gbk) COLLATE gbk_chinese_ci asc");
        Page<AssetFixed> page = new Page<AssetFixed>(pageNo, pageSize);
        IPage<AssetFixed> pageList = assetFixedService.page(page, queryWrapper);
        for (int i = 0; i < pageList.getRecords().size(); i++) {
            AssetFixed assetFixed = pageList.getRecords().get(i);
            List<ActBusiness> list = actBusinessService.list(new QueryWrapper<ActBusiness>().eq("status", "1").eq("table_name", "zcgl_recipients").like("data", assetFixed.getId()));
            if (list.size() > 0) {
                Double count = 0.0;
                for (int j = 0; j < list.size(); j++) {
                    ActBusiness actBusiness = list.get(j);
                    JSONObject data = JSON.parseObject(actBusiness.getData());
                    JSONArray jsonArray = data.getJSONArray("zcglRecipientsAssetsList");
                    for (int k = 0; k < jsonArray.size(); k++) {

                        if (assetFixed.getSpecifications() == null) {

                            assetFixed.setSpecifications("");
                        }


                        if (assetFixed.getSpecifications().equals(jsonArray.getJSONObject(k).get("assetSpecifications").toString())
                                && assetFixed.getCode().equals(jsonArray.getJSONObject(k).get("assetCode").toString())
                                && assetFixed.getAssetFixedCategoryId().equals(assetFixedService.getById(jsonArray.getJSONObject(k).get("assetId").toString()).getAssetFixedCategoryId())
                        ) {
                            count += Double.valueOf(jsonArray.getJSONObject(k).get("assetAmount").toString());

                        }
                    }
                }
                //显示流程中的数量
                assetFixed.setLcCount(new BigDecimal(count));
                //显示可以入库的数量 因为有的在流程中审核，已经被占用数量
                assetFixed.setTrueCount(assetFixed.getAmount().subtract(new BigDecimal(count)));
            } else {
                assetFixed.setTrueCount(assetFixed.getAmount());
                assetFixed.setLcCount(new BigDecimal(0.0));
            }
        }
        return Result.ok(pageList);
    }

    /**
     * 分页列表查询
     *
     * @param
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "仓库-分页列表查询")
    @ApiOperation(value = "仓库-分页列表查询", notes = "仓库-分页列表查询")
    @GetMapping(value = "/ckList")
    public Result<?> ckList(AssetFixed assetFixed1,
                            @RequestParam(required = false, name = "type") String type,
                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                            HttpServletRequest req) {
        //0才是未删除的
        assetFixed1.setDelFlag(0);
        System.out.println("开始");
        QueryWrapper<AssetFixed> queryWrapper = QueryGenerator.initQueryWrapper(assetFixed1, req.getParameterMap());
        if ("safe".equals(assetFixed1.getSafeType())) {

            queryWrapper.apply("amount < jiexian");

        }
        if ("2".equals(type)) {
            queryWrapper.apply("amount >0");

        }
        if (oConvertUtils.isNotEmpty(assetFixed1.getAssetFixedCategoryId())) {
            queryWrapper.or().apply(" asset_fixed_category_id in (select id from zcgl_asset_fixed_category where parent_id ='" + assetFixed1.getAssetFixedCategoryId() + "')");
        }

        queryWrapper.apply("asset_fixed_category_id is not null");
        Page<AssetFixed> page = new Page<AssetFixed>(pageNo, pageSize);
        IPage<AssetFixed> pageList = assetFixedService.page(page, queryWrapper);
        System.out.println(pageList.getRecords() + "查看结果");
        for (int i = 0; i < pageList.getRecords().size(); i++) {
            AssetFixed assetFixed = pageList.getRecords().get(i);
            List<ActBusiness> list = actBusinessService.list(new QueryWrapper<ActBusiness>().eq("status", "1").eq("table_name", "zcgl_recipients").like("data", assetFixed.getId()));
            if (list.size() > 0) {
                Double count = 0.0;
                for (int j = 0; j < list.size(); j++) {
                    ActBusiness actBusiness = list.get(j);
                    JSONObject data = JSON.parseObject(actBusiness.getData());
                    JSONArray jsonArray = data.getJSONArray("zcglRecipientsAssetsList");
                    for (int k = 0; k < jsonArray.size(); k++) {

                        if (assetFixed.getSpecifications() == null) {

                            assetFixed.setSpecifications("");
                        }


                        if (assetFixed.getSpecifications().equals(jsonArray.getJSONObject(k).get("assetSpecifications").toString())
                                && assetFixed.getCode().equals(jsonArray.getJSONObject(k).get("assetCode").toString())
                                && assetFixed.getAssetFixedCategoryId().equals(assetFixedService.getById(jsonArray.getJSONObject(k).get("assetId").toString()).getAssetFixedCategoryId())

                        ) {
                            count += Double.valueOf(jsonArray.getJSONObject(k).get("assetAmount").toString());

                        }
                    }
                }
                //显示流程中的数量
                assetFixed.setLcCount(new BigDecimal(count));
                //显示可以入库的数量 因为有的在流程中审核，已经被占用数量
                assetFixed.setTrueCount(assetFixed.getAmount().subtract(new BigDecimal(count)));
            } else {
                assetFixed.setTrueCount(assetFixed.getAmount());
                assetFixed.setLcCount(new BigDecimal(0.0));
            }
        }
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param assetFixed
     * @return
     */
    @AutoLog(value = "固定资产-添加")
    @ApiOperation(value = "固定资产-添加", notes = "固定资产-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody AssetFixed assetFixed) {

//        if (assetFixed.getAssetType().contains("BGYP")) {
        if (true) {



            //此时需要去判断该类型总共有多少条了，自动生成资产的编码
            int count = assetFixedService.getTypeCount(assetFixed.getAssetType()) + 1;
            List<String> list = new ArrayList<String>();
            if (String.valueOf(count).length() < 4) {
                for (int i = 0; i < 4 - String.valueOf(count).length(); i++) {
                    list.add("0");
                }
            }
            String result = list.toString().replace("[", "").replace("]", "") + String.valueOf(count);
            if (assetFixed.getAssetType().contains("BGYP")) {
                //如果是办公用品的话，需要使用小类别的编码
                assetFixed.setCode(assetFixed.getBgypType() + "-" + result.replace(", ", ""));
            } else {
                assetFixed.setCode(assetFixed.getAssetType() + "-" + result.replace(", ", ""));
            }


            if (assetFixed.getAssetType().contains("CHWZ")

            ) {
                //如果是存货物资的话，需要使用小类别的编码
                assetFixed.setCode(assetFixed.getChwzType() + "-" + result.replace(", ", ""));
            } else {
                if (assetFixed.getAssetType().contains("BGYP") == false)
                    assetFixed.setCode(assetFixed.getAssetType() + "-" + result.replace(", ", ""));
            }

            assetFixed.setAmount(new BigDecimal(0.0));
            assetFixed.setPrice(new BigDecimal(0.0));

            AssetFixed assetFixed1 = new AssetFixed();
            if (assetFixed.getSpecifications() != null) {
                 assetFixed1 = assetFixedService.getOne(new QueryWrapper<AssetFixed>().eq("name", assetFixed.getName()).eq("specifications", assetFixed.getSpecifications()).eq("del_flag", 0));


            }else{

                 assetFixed1 = assetFixedService.getOne(new QueryWrapper<AssetFixed>().eq("name", assetFixed.getName()).eq("del_flag", 0));

            }


            if (assetFixed1 == null) {
                assetFixedService.save(assetFixed);
                return Result.ok("添加成功！");
            } else {

                return Result.error("添加失败！该名称和型号的物资已经存在");
            }

        }else{

            assetFixed.setAmount(new BigDecimal(0.0));
            assetFixed.setPrice(new BigDecimal(0.0));

            AssetFixed assetFixed1 = assetFixedService.getOne(new QueryWrapper<AssetFixed>().eq("name", assetFixed.getName()).eq("specifications", assetFixed.getSpecifications()).eq("del_flag", 0));

            if (assetFixed1 == null) {
                assetFixedService.save(assetFixed);
                return Result.ok("添加成功！");
            } else {

                return Result.error("添加失败！该名称和型号的物资已经存在");
            }


        }









    }

    /**
     * 编辑
     *
     * @param assetFixed
     * @return
     */
    @AutoLog(value = "固定资产-编辑")
    @ApiOperation(value = "固定资产-编辑", notes = "固定资产-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody AssetFixed assetFixed) {
        AssetFixed assetFixed1 = assetFixedService.getById(assetFixed.getId());
        int count = 0;
        if (assetFixed1.getAssetType().equals(assetFixed.getAssetType())) {
            count = assetFixedService.getTypeCount(assetFixed.getAssetType());
        } else {
            count = assetFixedService.getTypeCount(assetFixed.getAssetType()) + 1;
            List<String> list = new ArrayList<String>();
            if (String.valueOf(count).length() < 4) {
                for (int i = 0; i < 4 - String.valueOf(count).length(); i++) {
                    list.add("0");
                }
            }
            String result = list.toString().replace("[", "").replace("]", "") + String.valueOf(count);
            if (assetFixed.getAssetType().contains("BGYP")) {
                //如果是办公用品的话，需要使用小类别的编码
                assetFixed.setCode(assetFixed.getBgypType() + "-" + result.replace(", ", ""));
            } else {
                assetFixed.setCode(assetFixed.getAssetType() + "-" + result.replace(", ", ""));
            }
            if (assetFixed.getAssetType().contains("CHWZ")
            ) {
                //如果是存货物资的话，需要使用小类别的编码
                assetFixed.setCode(assetFixed.getChwzType() + "-" + result.replace(", ", ""));
            } else {
                if (assetFixed.getAssetType().contains("BGYP") == false)
                    assetFixed.setCode(assetFixed.getAssetType() + "-" + result.replace(", ", ""));
            }

        }
        if("".equals(assetFixed.getAssetFixedCategoryId())){
            assetFixed.setAssetFixedCategoryId(null);

        }
        if("".equals(assetFixed.getSpecifications())){
            assetFixed.setSpecifications(null);
        }

        List<AssetFixed> list = assetFixedService.list(new QueryWrapper<AssetFixed>().eq("code",assetFixed.getCode()));

        for (int i = 0; i < list.size(); i++) {
            AssetFixed assetFixed2 = list.get(i);
            assetFixed2.setSpecifications(assetFixed.getSpecifications());
            assetFixed2.setUnit(assetFixed.getUnit());
            assetFixed2.setName(assetFixed.getName());
            assetFixedService.editAssetFixed(assetFixed2);
        }

        assetFixedService.editAssetFixed(assetFixed);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "固定资产-通过id删除")
    @ApiOperation(value = "固定资产-通过id删除", notes = "固定资产-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        AssetFixed assetFixed = assetFixedService.getById(id);
        assetFixed.setDelFlag(1);

        List<ZcglPutStorageAssets> zcglPutStorageAssets = iZcglPutStorageAssetsService.list(new QueryWrapper<ZcglPutStorageAssets>().eq("asset_id", id));
        if (zcglPutStorageAssets.size() > 0) {
            return Result.error("该物资有入库记录，不允许删除！");
        }


        if (assetFixed.getAmount().compareTo(new BigDecimal(0.0)) == 1) {
            return Result.error("库存数量不为0，禁止删除!");
        } else {
            //        assetFixedService.delAssetFixed(id);
            assetFixedService.updateById(assetFixed);
            return Result.ok("删除成功!");
        }


    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "固定资产-批量删除")
    @ApiOperation(value = "固定资产-批量删除", notes = "固定资产-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        assetFixedService.delBatchAssetFixed(ids);
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "固定资产-通过id查询")
    @ApiOperation(value = "固定资产-通过id查询", notes = "固定资产-通过id查询")
    @RequestMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        AssetFixed assetFixed = assetFixedService.getById(id);
        //获取流程中的数量
        List<ActBusiness> list = actBusinessService.list(new QueryWrapper<ActBusiness>().eq("status", "1").eq("table_name", "zcgl_recipients").like("data", assetFixed.getId()));
        if (list.size() > 0) {
            Double count = 0.0;
            for (int j = 0; j < list.size(); j++) {
                ActBusiness actBusiness = list.get(j);
                JSONObject data = JSON.parseObject(actBusiness.getData());
                JSONArray jsonArray = data.getJSONArray("zcglRecipientsAssetsList");
                for (int k = 0; k < jsonArray.size(); k++) {

                    if (assetFixed.getSpecifications() == null) {

                        assetFixed.setSpecifications("");
                    }


                    if (assetFixed.getSpecifications().equals(jsonArray.getJSONObject(k).get("assetSpecifications").toString())
                            && assetFixed.getCode().equals(jsonArray.getJSONObject(k).get("assetCode").toString())
                            && assetFixed.getAssetFixedCategoryId().equals(assetFixedService.getById(jsonArray.getJSONObject(k).get("assetId").toString()).getAssetFixedCategoryId())
                    ) {
                        count += Double.valueOf(jsonArray.getJSONObject(k).get("assetAmount").toString());

                    }
                }
            }
            //显示流程中的数量
            assetFixed.setLcCount(new BigDecimal(count));
            //显示可以入库的数量 因为有的在流程中审核，已经被占用数量
            assetFixed.setTrueCount(assetFixed.getAmount().subtract(new BigDecimal(count)));
        } else {
            assetFixed.setTrueCount(assetFixed.getAmount());
            assetFixed.setLcCount(new BigDecimal(0.0));
        }

        return Result.ok(assetFixed);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param assetFixed
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AssetFixed assetFixed) {


        return super.exportXls(request, assetFixed, AssetFixed.class, "库存情况");
    }

    /**
     * 导出excel
     *
     * @param request
     * @param assetFixed
     */
    @RequestMapping(value = "/exportXls1")
    public ModelAndView exportXls1(HttpServletRequest request, AssetFixed assetFixed) {


        return this.exportXls(request, assetFixed, AssetFixed.class, "库存情况");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return assetFixedService.importExcel(request, response, AssetFixed.class);
    }


    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcelAsset", method = RequestMethod.POST)
    public Result<?> importExcelAsset(HttpServletRequest request, HttpServletResponse response) {
        return assetFixedService.importExcelAsset(request, response, AssetFixedPutImport.class);
    }
    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcelAssetLY", method = RequestMethod.POST)
    public Result<?> importExcelAssetLY(HttpServletRequest request, HttpServletResponse response) {
        return assetFixedService.importExcelAssetLY(request, response, AssetFixedLYImport.class);
    }

    /**
     * 导入模板下载
     *
     * @param request
     * @param assetFixed
     * @return
     */
    @RequestMapping(value = "/exportXlsTemplate")
    public ModelAndView downloadUserTemplate(HttpServletRequest request, AssetFixed assetFixed) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.CLASS, AssetFixed.class);
//        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("固定资产导入模板", "导出人：" + loginUser.getUsername(), "固定资产导入模板"));
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("固定资产导入模板", "导出人：" + loginUser.getUsername(), "固定资产导入模板"));
        mv.addObject(NormalExcelConstants.DATA_LIST, new ArrayList<>());
        return mv;
    }

    /**
     * 导入模板下载
     *
     * @param request
     * @param assetFixed
     * @return
     */
    @RequestMapping(value = "/downloadUserTemplateAsset")
    public ModelAndView downloadUserTemplateAsset(HttpServletRequest request, AssetFixed assetFixed) throws InvocationTargetException, IllegalAccessException {
        List<AssetFixed> list = assetFixedService.list(new QueryWrapper<AssetFixed>().eq("del_flag", 0).last("and   asset_fixed_category_id is null"));


        List<AssetFixedPutImport> importList = new ArrayList<>();
        for (AssetFixed assetFixed1 : list) {
            AssetFixedPutImport importItem = new AssetFixedPutImport();
            importItem.setName(assetFixed1.getName());
            importItem.setSpecifications(assetFixed1.getSpecifications());
            importList.add(importItem);
        }
        System.out.println("是否执行"+importList);

        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.CLASS, AssetFixedPutImport.class);
//        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("固定资产导入模板", "导出人：" + loginUser.getUsername(), "固定资产导入模板"));
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("入库2导入模板", "导出人：" + loginUser.getUsername(), "入库导入模板"));
        System.out.println(importList.size()+"总共多少条");
        mv.addObject(NormalExcelConstants.DATA_LIST, importList);
        return mv;
    }
    /**
     * 领用模板下载
     *
     * @param request
     * @param assetFixed
     * @return
     */
    @RequestMapping(value = "/downloadUserTemplateAssetLingYong")
    public ModelAndView downloadUserTemplateAssetLingYong(HttpServletRequest request, AssetFixed assetFixed) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.CLASS, AssetFixedLYImport.class);
//        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("固定资产导入模板", "导出人：" + loginUser.getUsername(), "固定资产导入模板"));
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("领用导入模板", "导出人：" + loginUser.getUsername(), "入库导入模板"));
        mv.addObject(NormalExcelConstants.DATA_LIST, new ArrayList<>());
        return mv;
    }
    /**
     * 新增审批--写资产记录
     *
     * @param paramVo
     * @return
     */
    @AutoLog(value = "新增审批-写资产记录")
    @ApiOperation(value = "新增审批-写资产记录", notes = "新增审批-写资产记录")
    @PostMapping(value = "/createLog")
    public Result<?> createLog(@RequestBody AssetFixedParamVo paramVo) {
        AssetFixed asset = assetFixedService.getById(paramVo.getId());
        if (Arrays.asList(new String[]{"1", "2"}).contains(paramVo.getType())) {
            List<AssetFixedLog> logList = assetFixedLogService.list(new LambdaQueryWrapper<AssetFixedLog>()
                    .eq(AssetFixedLog::getAssetFixedId, paramVo.getId())
                    .eq(AssetFixedLog::getStatus, CommonConstant.STATUS_0).eq(AssetFixedLog::getType, paramVo.getType()));
            if (logList != null && logList.size() > 0) {
                return Result.error("该固定资产有正在进行的流程审批!");
            }
            AssetFixedLog log = new AssetFixedLog();
            log.setAssetFixedId(asset.getId());
            log.setType(paramVo.getType());
            log.setRecordTime(new Date());
            log.setOldCategoryId(asset.getAssetFixedCategoryId());
            log.setNowCategoryId(paramVo.getAssetFixedCategoryId());
            log.setStatus(CommonConstant.STATUS_0);
            assetFixedLogService.save(log);
        } else if (Arrays.asList(new String[]{"3", "4"}).contains(paramVo.getType())) {
            List<AssetFixedMaintenance> assetFixedMaintenances = assetFixedMaintenanceService.list(new LambdaQueryWrapper<AssetFixedMaintenance>()
                    .eq(AssetFixedMaintenance::getAssetFixedId, paramVo.getId())
                    .eq(AssetFixedMaintenance::getStatus, CommonConstant.STATUS_0).eq(AssetFixedMaintenance::getType, paramVo.getType()));
            if (assetFixedMaintenances != null && assetFixedMaintenances.size() > 0) {
                return Result.error("该固定资产有正在进行的流程审批!");
            }
            AssetFixedMaintenance maintenance = new AssetFixedMaintenance();
            maintenance.setAssetFixedId(asset.getId());
            maintenance.setType(paramVo.getType());
            maintenance.setReason(paramVo.getReason());
            maintenance.setStatus(CommonConstant.STATUS_0);
            assetFixedMaintenanceService.save(maintenance);
        }
        return Result.ok("操作成功!");
    }

    /**
     * 获取对象ID
     *
     * @return
     */
    public static String getId(AssetFixed item) {
        try {
            return PropertyUtils.getProperty(item, "id").toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 导出excel
     *
     * @param request
     */
    protected ModelAndView exportXls(HttpServletRequest request, AssetFixed object, Class<AssetFixed> clazz, String title) {
        // Step.1 组装查询条件
        QueryWrapper<AssetFixed> queryWrapper = QueryGenerator.initQueryWrapper(object, request.getParameterMap());

        object.setDelFlag(0);
        if ("safe".equals(object.getSafeType())) {

            queryWrapper.apply("amount < jiexian");

        }
        queryWrapper.apply("amount >0");


        LoginUser sysUser = JwtUtil.getLoginUser();
//        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // Step.2 获取导出数据
        List<AssetFixed> pageList = assetFixedService.list(queryWrapper);
        List<AssetFixed> exportList = null;

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(CommonConstant.DEFAULT_SEPARATOR));
            exportList = pageList.stream().filter(item -> selectionList.contains(getId(item))).collect(Collectors.toList());
        } else {
            exportList = pageList;
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, title); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, clazz);
        System.out.println("我是什么" + sysUser.getRealname());
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }
}
